import React from 'react';
import {Spin, Card, Button, Table, Row, Form, Col} from 'antd';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
import PropTypes from 'prop-types';
import {saleOrderTransportType, saleOrderResultJudgeResult, currency,
    saleOrderPriceTerms, paymentType, saleOrderType} from '../Enum';
import routes from './routes';
import {PERMISSION} from './constants';
import {DATE_FORMAT, FORM_ROW_OPTIONS, FILES_API, DATETIME_FORMAT} from '../constants';
import {conventEnumValueToString, formatAmount, formatDateTime} from '../utils';
import {getDetail, abandonData, submitData} from './api';
import {injectIntl} from './intl';
import {hasPermissions, uuid} from './utils';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import TextInput from 'Shared/components/TextInput';
import {rejectValidator} from './validator';
import styles from './style.css';
const {Description} = DescriptionList;
const FormItem = Form.Item;
class ApprovePanel extends React.PureComponent {
    state = {
        isFetching: false,
        data: {},
        details: [],
        saleOrderResults: []
    }
    componentDidMount() {
        this.getDetailInfo();
    }
    getDetailInfo = () => {
        const id = this.props.id;
        this.setState({isFetching: true});
        getDetail(id)
            .then(res => {
                if(res.ok)
                    this.setState({
                        isFetching: false,
                        data: res.data,
                        attachments: res.data.attachments,
                        details: res.data.details.map(v => Object.assign({}, v, {
                            isDealerUser: this.props.isDealerUser,
                            id: uuid()
                        })),
                        saleOrderResults: res.data.saleOrderResults.map(item => Object.assign(item, {id: uuid()}))
                    });
                else
                    this.setState(({
                        isFetching: false
                    }));
            });
    }
    onCancel = () => {
        this.props.history.push(routes.query.url());
    }
    onClickSubmitBtn = () => {
        this.setState({loading: true});
        const data = {
            rowVersion: this.state.data.rowVersion
        };
        submitData(this.state.data.id, data)
            .then(res => {
                this.setState({loading: false});
                if(res.ok)
                    this.props.successReturn();
            });
    }
    onClickAbandon = () => {
        this.setState({loading: true});
        const data = {
            rowVersion: this.state.data.rowVersion
        };
        abandonData(this.state.data.id, data)
            .then(res => {
                this.setState({loading: false});
                if(res.ok)
                    this.props.successReturn();
            });
    }
    onSubmit = () => {
        const {data} = this.state;
        const isValid = rejectValidator(data);
        if(!isValid) {
            this.setState({
                validate: true
            });
            return;
        }
        this.setState({loading: true});
        this.props.onSubmit(data).then(res => {
            if(res.success)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }
    onSubmitMoney = num => {
        const {data} = this.state;
        data.status = num;
        if(num === 1 && !data.approveComment)
            data.approveComment = '资金往来确认 款未到';
        if(num === 0 && !data.approveComment)
            data.approveComment = '资金往来确认 款已到';
        const isValid = rejectValidator(data);
        if(!isValid) {
            this.setState({
                validate: true
            });
            return;
        }
        this.setState({loading: true});
        this.props.onSubmit(data).then(res => {
            if(res.success)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }
    onCancelApprove = () => {
        const {data} = this.state;
        this.setState({loading: true});
        this.props.onCancelApprove(data).then(res => {
            if(res.success)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }
    onSubmitReject = () => {
        const {data} = this.state;
        console.log(data);
        const isValid = rejectValidator(data);
        if(!isValid) {
            this.setState({
                validate: true
            });
            return;
        }
        this.setState({loading: true});
        this.props.onSubmitReject(data).then(res => {
            if(res.success)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }
    onChange = (value, name) => {
        const data = Object.assign({}, this.state.data, {
            [name]: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    }
    render() {
        const {data, attachments = []} = this.state;
        const {formatMessage} = this.props.intl;
        const operations = [];
        let totalProductCategory = 0;
        const totalProductCategoryArr = [];
        let totalProductCategoryNum = 0;
        this.state.details.forEach(o => {
            if(o.productCategoryCode) 
                if(totalProductCategoryArr.length === 0)
                    totalProductCategoryArr.push({
                        productCategoryCode: o.productCategoryCode
                    });
                else {
                    const index = totalProductCategoryArr.findIndex(v => v.productCategoryCode === o.productCategoryCode);
                    if(index === -1)
                        totalProductCategoryArr.push({
                            productCategoryCode: o.productCategoryCode
                        });
                }
            
            totalProductCategory = totalProductCategoryArr.length;
            totalProductCategoryNum += o.quantity;
        });
        if(hasPermissions(this.props.permissions, PERMISSION.update) && hasPermissions(data.options, PERMISSION.update))
            operations.push(<Button key="update" href={`#${routes.update.format(this.props.id)}`} size="small">{
                formatMessage({
                    id: 'approvePanel.update',
                    defaultMessage: '编辑'
                })
            }</Button>);
        if(hasPermissions(this.props.permissions, PERMISSION.generalManagerApprove) && hasPermissions(data.options, PERMISSION.generalManagerApprove))
            operations.push(<Button key="generalManagerApprove" href={`#${routes.finalApprove.format(this.props.id)}`} size="small">{
                formatMessage({
                    id: 'approvePanel.generalManagerApprove',
                    defaultMessage: '终审'
                })
            }</Button>);
        if(hasPermissions(this.props.permissions, PERMISSION.operationDepartmentApprove) && hasPermissions(data.options, PERMISSION.operationDepartmentApprove))
            operations.push(<Button key="operationDepartmentApprove" href={`#${routes.finalApprove.format(this.props.id)}`} size="small">{
                formatMessage({
                    id: 'approvePanel.operationDepartmentApprove',
                    defaultMessage: '终审'
                })
            }</Button>);
        if(hasPermissions(this.props.permissions, PERMISSION.submit) && hasPermissions(data.options, PERMISSION.submit))
            operations.push(<WrappedPopconfirm
                key="submit"
                id={this.props.id}
                placement="topLeft"
                onConfirm={this.onClickSubmitBtn}
                title={formatMessage({
                    id: 'approvePanel.validate.submit',
                    defaultMessage: '是否确认提交？'
                })}>
                <Button key="submit" size="small">{
                    formatMessage({
                        id: 'approvePanel.save',
                        defaultMessage: '提交'
                    })
                }</Button>
            </WrappedPopconfirm>);
        if(hasPermissions(this.props.permissions, PERMISSION.approve) && hasPermissions(data.options, PERMISSION.approve))
            operations.push(<Button key="approve" href={`#${routes.approve.format(this.props.id)}`} size="small">{
                formatMessage({
                    id: 'approvePanel.approve',
                    defaultMessage: '审核'
                })
            }</Button>);
        if(hasPermissions(this.props.permissions, PERMISSION.abandon) && hasPermissions(data.options, PERMISSION.abandon))
            operations.push(<WrappedPopconfirm
                key="abandon"
                id={this.props.id}
                placement="topLeft"
                onConfirm={this.onClickAbandon}
                title={formatMessage({
                    id: 'approvePanel.validate.abandon',
                    defaultMessage: '是否确认作废？'
                })}>
                <Button key="abandon" size="small">{
                    formatMessage({
                        id: 'approvePanel.abandon',
                        defaultMessage: '作废'
                    })
                }</Button>
            </WrappedPopconfirm>);
        const colums = [{
            title: formatMessage({
                id: 'approvePanel.column.serialNums',
                defaultMessage: '序号'
            }),
            dataIndex: 'serialNums',
            width: 120,
        }, {
            title: formatMessage({
                id: 'approvePanel.column.piCode',
                defaultMessage: 'PI编号'
            }),
            dataIndex: 'piCode',
            width: 120,
        }, {
            title: formatMessage({
                id: 'approvePanel.column.piSubmitTime',
                defaultMessage: '提报时间'
            }),
            dataIndex: 'piSubmitTime',
            width: 120,
            render: text => formatDateTime(text, DATE_FORMAT)
        }, {
            title: formatMessage({
                id: 'approvePanel.column.descriptionOfGoods',
                defaultMessage: '产品描述'
            }),
            dataIndex: 'descriptionOfGoods',
            width: 200,
        }, {
            title: formatMessage({
                id: 'approvePanel.column.kdBomCode',
                defaultMessage: 'KDBOM号'
            }),
            dataIndex: 'kdBomCode',
            width: 200,
        }, {
            title: formatMessage({
                id: 'approvePanel.column.kdBomVersionCode',
                defaultMessage: 'KDBOM版本号'
            }),
            dataIndex: 'kdBomVersionCode',
            width: 200,
        }, {
            title: formatMessage({
                id: 'approvePanel.column.productCategoryCode',
                defaultMessage: '车型编号'
            }),
            dataIndex: 'productCategoryCode',
            width: 200,
        }, {
            title: formatMessage({
                id: 'approvePanel.column.productCategoryName',
                defaultMessage: '车型名称'
            }),
            dataIndex: 'productCategoryName',
            width: 200,
        }, {
            title: formatMessage({
                id: 'approvePanel.column.engineModel',
                defaultMessage: '发动机型号'
            }),
            dataIndex: 'engineModel',
            width: 200,
        }, {
            title: formatMessage({
                id: 'approvePanel.column.transmission',
                defaultMessage: '手自动'
            }),
            dataIndex: 'transmission',
            width: 120,
        }, {
            title: formatMessage({
                id: 'approvePanel.column.quantity',
                defaultMessage: '数量'
            }),
            dataIndex: 'quantity',
            width: 120,
        }, {
            title: formatMessage({
                id: 'approvePanel.column.price',
                defaultMessage: '单价'
            }),
            dataIndex: 'price',
            width: 120,
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'approvePanel.column.totalPrice',
                defaultMessage: '总价'
            }),
            dataIndex: 'totalPrice',
            width: 120,
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'approvePanel.column.containerNumber',
                defaultMessage: '集装箱数'
            }),
            dataIndex: 'containerNumber',
            width: 120,
        }, {
            title: formatMessage({
                id: 'approvePanel.column.batchNumber',
                defaultMessage: '批次号'
            }),
            dataIndex: 'batchNumber',
            width: 120,
        }];
        const approveColums = [{
            title: formatMessage({
                id: 'approvePanel.column.approveSequence',
                defaultMessage: '审核序号'
            }),
            dataIndex: 'approveSequence',
            width: 120,
        }, {
            title: formatMessage({
                id: 'approvePanel.column.approverCode',
                defaultMessage: '审核人编号'
            }),
            dataIndex: 'approverCode',
            width: 120,
        }, {
            title: formatMessage({
                id: 'approvePanel.column.approverName',
                defaultMessage: '审核人姓名'
            }),
            dataIndex: 'approverName',
            width: 120,
        }, {
            title: formatMessage({
                id: 'approvePanel.column.approveTime',
                defaultMessage: '审核时间'
            }),
            dataIndex: 'approveTime',
            width: 120,
            render: text => formatDateTime(text, 'YYYY-MM-DD h:mm:ss')
        }, {
            title: formatMessage({
                id: 'approvePanel.column.approveComment',
                defaultMessage: '审核意见'
            }),
            dataIndex: 'approveComment',
            width: 300,
        }, {
            title: formatMessage({
                id: 'approvePanel.column.approveResult',
                defaultMessage: '判定结果'
            }),
            dataIndex: 'approveResult',
            width: 300,
            render: text => conventEnumValueToString(saleOrderResultJudgeResult, text)
        }, {
            title: formatMessage({
                id: 'approvePanel.column.nextOperation',
                defaultMessage: '下一步操作'
            }),
            dataIndex: 'nextOperation',
            width: 300,
        }];
        return (
            <div>
                <Spin spinning={this.state.isFetching}>
                    <Card>
                        <DescriptionList title={<Row><Col span={6}>{
                            formatMessage({
                                id: 'approvePanel.card.partOtherOrder',
                                defaultMessage: '订单信息'
                            })
                        }</Col>
                        <Col className={`col-align-right ${styles.detail}`} span={18}>{operations}</Col></Row>}>
                            <Description term={formatMessage({
                                id: 'approvePanel.operation.code',
                                defaultMessage: '订单编号'
                            })}>{data.code}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detail.operation.dealer',
                                defaultMessage: '总代'
                            })}>({data.dealerCode}){data.dealerName}</Description>
                            <Description term={formatMessage({
                                id: 'approvePanel.operation.currency',
                                defaultMessage: '币种'
                            })}>{conventEnumValueToString(currency, data.currency)}</Description>
                            <Description term={formatMessage({
                                id: 'detail.operation.country',
                                defaultMessage: '国家'
                            })}>{data.country}</Description>
                            <Description term={formatMessage({
                                id: 'detail.operation.brandName',
                                defaultMessage: '品牌'
                            })}>{data.brandName}</Description>
                            <Description term={formatMessage({
                                id: 'approvePanel.operation.tradeMethodName',
                                defaultMessage: '贸易方式名称'
                            })}>{data.tradeMethodName}</Description>
                            <Description term={formatMessage({
                                id: 'approvePanel.operation.salesOrderPriceTerms',
                                defaultMessage: '价格条款'
                            })}>{conventEnumValueToString(saleOrderPriceTerms, data.salesOrderPriceTerms)}</Description>

                            <Description term={formatMessage({
                                id: 'approvePanel.operation.orderType',
                                defaultMessage: '订单类型'
                            })}>{conventEnumValueToString(saleOrderType, data.orderType)}</Description>
                            <Description term={formatMessage({
                                id: 'approvePanel.operation.transportType',
                                defaultMessage: '运输方式'
                            })}>{conventEnumValueToString(saleOrderTransportType, data.transportType)}</Description>
                            <Description term={formatMessage({
                                id: 'approvePanel.operation.paymentType',
                                defaultMessage: '付款方式'
                            })}>{conventEnumValueToString(paymentType, data.paymentType)}</Description>
                            <Description term={formatMessage({
                                id: 'approvePanel.operation.account',
                                defaultMessage: '到付账号'
                            })}>{data.account}</Description>
                            <Description term={formatMessage({
                                id: 'approvePanel.operation.carrierName',
                                defaultMessage: '指定货代'
                            })}>{data.carrierName}</Description>
                            <Description term={formatMessage({
                                id: 'approvePanel.operation.shippingPortName',
                                defaultMessage: '发货港口名称'
                            })}>{data.shippingPortName}</Description>
                            <Description term={formatMessage({
                                id: 'approvePanel.operation.destinationPort',
                                defaultMessage: '目的港口'
                            })}>{data.destinationPort}</Description>
                            <Description term={formatMessage({
                                id: 'approvePanel.operation.vinYear',
                                defaultMessage: 'VIN码年份'
                            })}>{data.vinYear}</Description>
                            <Description term={formatMessage({
                                id: 'approvePanel.operation.deliveryDate',
                                defaultMessage: '需求交期'
                            })}>{formatDateTime(data.deliveryDate, DATE_FORMAT)}</Description>
                            <Description term={formatMessage({
                                id: 'approvePanel.operation.batchNumber',
                                defaultMessage: '批次号'
                            })}>{data.batchNumber}</Description>
                            <Description term={formatMessage({
                                id: 'approvePanel.operation.totalAmount',
                                defaultMessage: '总金额'
                            })}>{formatAmount(data.totalAmount)}</Description>
                            
                        </DescriptionList>
                        <Form style={{
                            marginTop: '20px',
                            marginRight: '100px'
                        }}>
                            <Row>
                                <Col>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.remark',
                                        defaultMessage: '备注'
                                    })} {...FORM_ROW_OPTIONS.item}>
                                        <TextInput
                                            type="textarea"
                                            name="remark"
                                            value={data.remark}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <Col>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.approveComment',
                                        defaultMessage: '审核意见'
                                    })} {...FORM_ROW_OPTIONS.item}
                                    required={!data.isFundIntercourse}>
                                        <TextInput
                                            type="textarea"
                                            name="approveComment"
                                            value={data.approveComment}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                        </Form>
                    </Card>
                    <Card>
                        <DescriptionList title={formatMessage({
                            id: 'approvePanel.table.details',
                            defaultMessage: '清单'
                        })}>
                            <Table
                                className="white-space-nowrap"
                                columns={colums}
                                rowKey="id"
                                dataSource={this.state.details}
                                pagination={false}
                                size="small"
                                bordered={true}
                                footer={() => (<DescriptionList>
                                    <Description term={formatMessage({
                                        id: 'detailPanel.operation.totalProductCategory',
                                        defaultMessage: '车型汇总'
                                    })}>{totalProductCategory ? totalProductCategory : null}
                                    </Description>
                                    <Description term={formatMessage({
                                        id: 'detailPanel.operation.totalProductCategoryNum',
                                        defaultMessage: '车型数量汇总'
                                    })}>{totalProductCategoryNum ? totalProductCategoryNum : null}
                                    </Description>
                                    <Description term={formatMessage({
                                        id: 'detailPanel.operation.fee',
                                        defaultMessage: '金额汇总显示'
                                    })}>{formatAmount(data.totalAmount ? data.totalAmount : null)}
                                    </Description>
                                </DescriptionList>)}/>
                        </DescriptionList>
                    </Card>
                    <Card>
                        <DescriptionList title={formatMessage({
                            id: 'approvePanel.table.saleOrderResults',
                            defaultMessage: '审核意见'
                        })}>
                            <Table
                                className="white-space-nowrap"
                                columns={approveColums}
                                rowKey="id"
                                dataSource={this.state.saleOrderResults}
                                pagination={false}
                                size="small"
                                bordered={true} />
                        </DescriptionList>
                    </Card>
                    <Card title={formatMessage({
                        id: 'detailPanel.details.attachment',
                        defaultMessage: '附件清单'
                    })}>
                        {attachments && attachments.length >= 0
                            ? <DescriptionList>
                                {attachments.map(item => (<Description key={item.fileId}>
                                    <a icon="download" download href={`${FILES_API.files}/${item.fileId}`} size="small">
                                        {item.fileName}</a></Description>))}
                            </DescriptionList>
                            : <DescriptionList title={formatMessage({
                                id: 'detailPanel.content.noAttachment',
                                defaultMessage: '暂无附件'
                            })} />}
                    </Card>
                    {
                        ((data.nextApproveNumber === 1 || data.nextApproveNumber === 2 || data.nextApproveNumber === 5) && !data.isFundIntercourse) &&
                        <Card className={styles.optionBtn}>
                            <Button
                                style={{marginRight: '10px'}}
                                onClick={this.onSubmitReject}>
                                {formatMessage({
                                    id: 'approvePanel.operation.onSubmitReject',
                                    defaultMessage: '驳回'
                                })}
                            </Button>
                            <Button
                                type="primary"
                                style={{marginRight: '10px'}}
                                onClick={this.onSubmit}>
                                {formatMessage({
                                    id: 'approvePanel.operation.onSave',
                                    defaultMessage: '通过'
                                })}
                            </Button>
                        </Card>
                    }
                    {
                        data.isFundIntercourse &&
                        <Card className={styles.optionBtn}>
                            <Button
                                type="primary"
                                style={{marginRight: '10px'}}
                                onClick={() => this.onSubmitMoney(1)}>
                                {formatMessage({
                                    id: 'approvePanel.operation.notReceived',
                                    defaultMessage: '款未到'
                                })}
                            </Button>
                            <Button
                                type="primary"
                                style={{marginRight: '10px'}}
                                onClick={() => this.onSubmitMoney(0)}>
                                {formatMessage({
                                    id: 'approvePanel.operation.receive',
                                    defaultMessage: '款已到'
                                })}
                            </Button>

                        </Card>
                    }
                    {
                        (data.nextApproveNumber === 4 && !data.isFundIntercourse) &&
                        <Card className={styles.optionBtn}>
                            <Button
                                type="primary"
                                style={{marginRight: '10px'}}
                                onClick={this.onSubmit}>
                                {formatMessage({
                                    id: 'approvePanel.operation.onSave',
                                    defaultMessage: '通过'
                                })}
                            </Button>
                            <Button
                                onClick={this.onCancelApprove}>
                                {formatMessage({
                                    id: 'approvePanel.operation.onCancel',
                                    defaultMessage: '财务取消'
                                })}
                            </Button>
                        </Card>
                    }
                </Spin>
                <div className="page-toolbar">
                    <Button type="primary" onClick={this.onCancel}>{this.props.intl.formatMessage({
                        id: 'approvePanel.operation.cancel',
                        defaultMessage: '返回'
                    })}</Button>
                </div>
            </div>
        );
    }
}

ApprovePanel.propTypes = {
    permissions: PropTypes.array.isRequired,
    successReturn: PropTypes.func.isRequired,
    onCancelApprove: PropTypes.func.isRequired,
    onSubmit: PropTypes.func.isRequired,
    onSubmitReject: PropTypes.func.isRequired,
    history: PropTypes.object,
    id: PropTypes.string,
    intl: PropTypes.object,
    isDealerUser: PropTypes.bool,
};

import {connect} from 'react-redux';
import {tableSearch, onApprove, onReject, onCancelApprove} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const mapStateToProps = (state, props) => ({
    permissions: getPermissions(state),
    isDealerUser: state.getIn((['page', 'domainData', 'initData', 'isDealerUser'])),
});
const mapDispatchToProps = (dispatch, props) => ({
    onSubmit: (data, details) => dispatch(onApprove(data, details)),
    onCancelApprove: (data, details) => dispatch(onCancelApprove(data, details)),
    onSubmitReject: (data, details) => dispatch(onReject(data, details)),
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(ApprovePanel));
